//
//  CommonWebViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/21.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "CommonWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "InfoShareView.h"
#import "QRCodeViewController.h"
@interface CommonWebViewController ()<UIWebViewDelegate,UIScrollViewDelegate,InfoShareViewDelegate>
{
   InfoShareView *_shareView;
   NSString *_promoteImg;
}
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIActivityIndicatorView *activity;
@end

@implementation CommonWebViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_shareView) {
        [_shareView cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (_naviTitle.length > 0) {
        [self initNavBarTitle:_naviTitle andLeftItemName:@"返回" andRightItemName:@""];
    }else {
        [self initNavBarTitle:@"随取宝" andLeftItemName:@"返回" andRightItemName:@""];
    }
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self initView];
}

- (void)viewDidLayoutSubviews {
    _webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
   
}


- (void)judgeJump {
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //定义好JS要调用的方法, login就是调用的login方法名
    context[@"back"] = ^() {
        // DLOG(@"back+++++++Begin Log+++++++");
        NSArray *args = [JSContext currentArguments];
       
        if ([_typeStr isEqualToString:@"CheckAdvantage"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoShareTab" object:nil];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else if ([_typeStr isEqualToString:@"InviteRule"]) {
            [self shareView];
        }else {
            if (self.delegate && [self.delegate respondsToSelector:@selector(backAction)]) {
                [self.delegate backAction];
            }
        }
        for (JSValue *jsVal in args) {
           // DLOG(@"%@", jsVal.toString);
        }
        
        // DLOG(@"-------End Log-------");
    };
}
- (void)shareView{
    _shareView = [[InfoShareView alloc] init];
    _shareView.delegate = self;
    _shareView.shareTitle = @"快来投资理财吧!";
    _shareView.shareContent = [NSString stringWithFormat:@"随取宝APP全新面世!%@",@""];
    _shareView.shareImage = @"";
    _shareView.shareUrl = [NSString stringWithFormat:@"%@/reg?recommendName=%@",Baseurl,AppDelegateInstance.userInfo.userName];
    [_shareView show];
 
}
#pragma mark - Delegate
- (void)shareMoreViewDidSelectWithShareType:(ShareType)shareType {
    if (shareType == ShareTypeOther) {
        QRCodeViewController *codeVc = [[QRCodeViewController alloc] init];
        codeVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:codeVc animated:YES];
    }else {
        [self shareDataWithShareType:shareType];
    }
}

- (void)shareDataWithShareType:(ShareType)shareType {
    //构造分享内容
    NSString *url;
    if (AppDelegateInstance.userInfo.spreadLink.length > 0) {
        url = AppDelegateInstance.userInfo.spreadLink;
    }else {
        url = [NSString stringWithFormat:@"%@/app/share",Baseurl];
    }
    
    id<ISSContent> publishContent;
    if (_promoteImg.length > 0) {
        publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@%@",@"随取宝app全新面世!随存随取 8秒注册赢好礼!",url]
                            defaultContent:@""
                                     image:[ShareSDK pngImageWithImage:[UIImage imageNamed:@"app_logo"]]
                                     title:@"随取宝送大礼了！"
                                       url:url
                               description:@""
                                 mediaType:SSPublishContentMediaTypeNews];
    }else {
        publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@%@",@"随取宝app全新面世!随存随取 8秒注册赢好礼!",url]
                            defaultContent:@""
                                     image:[ShareSDK pngImageWithImage:[UIImage imageNamed:@"app_logo"]]
                                     title:@"随取宝送大礼了！"
                                       url:url
                               description:@""
                                 mediaType:SSPublishContentMediaTypeNews];
    }
    
    
    [ShareSDK shareContent:publishContent
                      type:shareType
               authOptions:nil
              shareOptions:nil
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state,
                             id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        if (state == SSResponseStateSuccess) {
                            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"分享成功", nil)];
                            // DLOG(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                        }else if (state == SSResponseStateFail) {
                            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"分享失败", nil)];
                            // DLOG(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                        }else {
                            // DLOG(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                        }
                    }];
}


#pragma mark ------webview代理
-(void)webViewDidStartLoad:(UIWebView *)webView {
    [_activity startAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    [_activity stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    [self judgeJump];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [_activity stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)setRequestUrl:(NSString *)requestUrl {
    _requestUrl = requestUrl;
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:_requestUrl] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60.0];
    [_webView loadRequest:request];
}

#pragma mark - View
- (void)initView {
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, MSWIDTH, MSHIGHT - 64)];
    _webView.userInteractionEnabled = YES;
    _webView.delegate = self;
    _webView.opaque = NO;
    _webView.scrollView.scrollEnabled = YES;
    _webView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_webView];
    if (_requestUrl.length > 0) {
        
        [self setRequestUrl:_requestUrl];
    }
    
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activity.center = _webView.center;
    [self.view addSubview:_activity];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
